package com.wswy.wzcx.ui.main.home;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.AppBarLayout.OnOffsetChangedListener;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.ICity;
import com.wswy.wzcx.model.home.ExtModule;
import com.wswy.wzcx.model.home.LabelModel;
import com.wswy.wzcx.model.home.RPaths;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.model.news.NewsCategory;
import com.wswy.wzcx.model.weather.WeatherData;
import com.wswy.wzcx.module.LocManager;
import com.wswy.wzcx.module.base.CBaseFragment;
import com.wswy.wzcx.module.weather.AmapWeatherManager;
import com.wswy.wzcx.module.weather.WeatherUtils;
import com.wswy.wzcx.statistics.BizReport;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.Constants;
import com.wswy.wzcx.ui.car.AddCarInfoActivity;
import com.wswy.wzcx.ui.car.choose.ChooseCityActivity;
import com.wswy.wzcx.ui.main.IScrollTopChild;
import com.wswy.wzcx.ui.main.IScrollTopHandler;
import com.wswy.wzcx.ui.main.MainActUtils;
import com.wswy.wzcx.ui.main.NewbieIndexHandler;
import com.wswy.wzcx.ui.main.ad.AdItemVo;
import com.wswy.wzcx.ui.main.ad.HomeAdViewModel;
import com.wswy.wzcx.ui.main.ad.InteractioDialog;
import com.wswy.wzcx.ui.main.home.component.HomeAdController;
import com.wswy.wzcx.ui.other.ClickUtils;
import com.wswy.wzcx.ui.other.DialogFactory;
import com.wswy.wzcx.ui.other.UpdateTools;
import com.wswy.wzcx.utils.FragUtils;
import com.wswy.wzcx.utils.UiUtils;
import com.wswy.wzcx.widget.UnderlinePageIndicator;
import com.wswy.wzcx.widget.home.HomeBehavior;
import com.wswy.wzcx.widget.home.HomeCategoryLayout;
import com.wswy.wzcx.widget.home.HomeExtSModulesLayout;
import com.wswy.wzcx.widget.home.HomeIndicatorView;
import com.wswy.wzcx.widget.home.ModuleItemClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import kotlin.random.Random;
import timber.log.Timber;

/**
 * 首页
 */
public class HomeFragment extends CBaseFragment implements IHomeView,
        IScrollTopChild, HomeNewsFragment.RVOnScrollListener {

    private static final int MSG_SHOW_FLOAT_AD = 1002;
    private static final int MSG_SHOW_CAR_TIP = 1005;

    private static final int REQ_CHOOSE_CITY = 2020;

    private static final String TAG = "HomeFragment";

    private SmartRefreshLayout refreshLayout;

    private TextView tvCity;
    private TextView tvWeather;
    private TextView tvWeatherTemp;

    private SimpleDraweeView imgAvatar;


    private ViewPager mViewPager;
    private HomeIndicatorView indicatorView;

    private LinearLayout layoutContent;
    private LinearLayout layoutExtModules;

    private ViewPager vpNews;

    //private HomeCarAdapter adapter;

    private HomeCarController homeCarController;

    private HomePresenter mPresenter;

    private AppBarLayout appBarLayout;

    private UnderlinePageIndicator indicator;

    private TabLayout tabLayout;

    //悬浮广告
    private View adFloat;

    private ViewFlipper vpAds;

    private IScrollTopHandler scrollTopHandler;
    private boolean showScrollTop = false;

    private NewbieIndexHandler newbieIndexHandler;

    private HomeNewsFragment currNewsFragment;

    private HomeAdController homeAdController;

    private static int screenW = ScreenUtils.getScreenWidth();

    private boolean isShownNotify = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof IScrollTopHandler) {
            scrollTopHandler = (IScrollTopHandler) context;
        }
        if (context instanceof NewbieIndexHandler) {
            newbieIndexHandler = (NewbieIndexHandler) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        scrollTopHandler = null;
        newbieIndexHandler = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_nav_home5, container, false);

        UiUtils.INSTANCE.injectStatusBar(inflate);
        return inflate;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        refreshLayout = view.findViewById(R.id.refreshLayout);
        tvCity = view.findViewById(R.id.tv_city);
        tvWeather = view.findViewById(R.id.tv_weather);
        tvWeatherTemp = view.findViewById(R.id.tv_weather_temp);
        imgAvatar = view.findViewById(R.id.img_avatar);
        mViewPager = view.findViewById(R.id.view_pager);
        indicatorView = view.findViewById(R.id.indicators);
        layoutContent = view.findViewById(R.id.layout_categories);
        layoutExtModules = view.findViewById(R.id.layout_ext_modules);
        vpNews = view.findViewById(R.id.vp_news);

        appBarLayout = view.findViewById(R.id.appbar);
        indicator = view.findViewById(R.id.indicator);
        tabLayout = view.findViewById(R.id.tabLayout);

        vpAds = view.findViewById(R.id.vf_ads);

        //点击

        tvCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtils.isFastClick()) {
                    return;
                }

                onClickCity();
            }
        });
        view.findViewById(R.id.ll_weather_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtils.isFastClick()) {
                    return;
                }
                onClickWeather();
            }
        });

        imgAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtils.isFastClick()) {
                    return;
                }
                onClickWeather();
            }
        });


        mViewPager.setOffscreenPageLimit(5);

        homeCarController = new HomeCarController(mViewPager, (FrameLayout) view.findViewById(R.id.fl_cars));
        homeCarController.flShadow = view.findViewById(R.id.sdl_view);

        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicatorView.setSelectedPosition(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        mPresenter = new HomePresenter(getContext(), this);
        mPresenter.onCreate(getArguments());
        mPresenter.requestLocation();

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mPresenter.loadMyCars(true);
                //新闻刷新
                if (currNewsFragment != null) {
                    currNewsFragment.reload();
                }
            }
        });


        appBarLayout.addOnOffsetChangedListener(new OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {

//        Log.e(TAG, "onOffsetChanged --> "+i+"   "+appBarLayout.getHeight());

                boolean st = Math.abs(i) >= appBarLayout.getHeight();
                if (scrollTopHandler != null) {
                    showScrollTop = st;

                    if (showScrollTop) {
                        scrollTopHandler.onShowTop();
                    } else {
                        scrollTopHandler.onHideTop();
                    }

                    if (homeAdController != null) {
                        homeAdController.changeShowAutoScroll(!showScrollTop);
                    }

                }

            }
        });

        homeAdController = new HomeAdController((ViewGroup) view.findViewById(R.id.fl_ad_container));

        final HomeAdViewModel homeAdViewModel = provideViewModelFromActivity(HomeAdViewModel.class);

        //轮播广告显示
        homeAdViewModel.getAdsLiveData().observe(this,
                new Observer<List<AdItemVo>>() {
                    @Override
                    public void onChanged(@Nullable List<AdItemVo> adItemVos) {
                        if (adItemVos != null) {
                            homeAdController.showAds(adItemVos);
                            homeAdViewModel.getAdsLiveData().removeObserver(this);
                        }

                    }
                });


        //弹窗广告
        homeAdViewModel.getAdInteractionLiveData().observe(this, new Observer<AdItemVo>() {
            @Override
            public void onChanged(@Nullable final AdItemVo adItemVo) {
                Context context = getContext();
                if (adItemVo != null && context != null) {

                    switch (adItemVo.getType()) {
                        case AdItemVo.SELF_IMG:
                            MainActUtils.addNextDialog(MainActUtils.DLG_KEY_AD, new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        InteractioDialog interactioDialog = new InteractioDialog(requireContext(),
                                                adItemVo);
                                        interactioDialog.setOnDismissListener(new OnDismissListener() {
                                            @Override
                                            public void onDismiss(DialogInterface dialog) {
                                                MainActUtils.checkAndShow(true);
                                            }
                                        });
                                        interactioDialog.show();
                                    } catch (Throwable e) {
                                        e.printStackTrace();
                                        MainActUtils.checkAndShow(true);
                                    }
                                }
                            });


                            break;
                        case AdItemVo.TTAD:
                            if (!isFinish()) {
                                FragmentActivity activity = getActivity();
                                if (activity != null) {
                                    homeAdViewModel.showTTADInteraction(activity);
                                }
                            }
                            break;
                    }
                }


            }
        });

        homeAdViewModel.getAdFloatLiveData().observe(this, new Observer<AdItemVo>() {
            @Override
            public void onChanged(@Nullable AdItemVo adItemVo) {
                if (adItemVo != null && getView() != null) {
                    ViewGroup rootLayout = (ViewGroup) getView();
                    //删除ad float
                    View viewById = rootLayout.findViewById(R.id.id_home_float_ad);
                    if (viewById != null) {
                        rootLayout.removeView(viewById);
                    }

                    View adView = adItemVo.getAdView();

                    ViewParent parent = adView.getParent();
                    if (parent instanceof ViewGroup) {
                        ((ViewGroup) parent).removeView(adView);
                    }

                    adView.setId(R.id.id_home_float_ad);
                    //adView.setVisibility(View.GONE);

                    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(SizeUtils.dp2px(64), SizeUtils.dp2px(64));
                    lp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
                    lp.rightMargin = SizeUtils.dp2px(10);
                    lp.bottomMargin = SizeUtils.dp2px(10);

                    rootLayout.addView(adView, lp);

                    adFloat = adView;
                }
            }
        });

        homeAdViewModel.getHomevpAdLiveData().observe(this, new Observer<List<AdModel>>() {
            @Override
            public void onChanged(@Nullable List<AdModel> adModels) {
                showHomeVpAds(adModels);
            }
        });

    }


    private void showHomeVpAds(List<AdModel> adModels) {
        if (adModels != null && !adModels.isEmpty()) {
            vpAds.setVisibility(View.VISIBLE);
            vpAds.removeAllViewsInLayout();
            View.OnClickListener clickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ClickUtils.isFastClick()) {
                        return;
                    }
                    Object tag = v.getTag();
                    if (tag instanceof AdModel) {
                        AdModel adModel = (AdModel) tag;
                        RouterUtils.startTarget(v.getContext(), adModel.linkTarget, adModel.linkUrl);
                    }

                }
            };

            for (AdModel adModel : adModels) {
                View adItemLayout = LayoutInflater.from(getContext())
                        .inflate(R.layout.layout_item_vf_ad, vpAds, false);
                TextView tvAdTitle = adItemLayout.findViewById(R.id.tv_title);

                tvAdTitle.setText(adModel.title);

                adItemLayout.setTag(adModel);
                adItemLayout.setOnClickListener(clickListener);

                vpAds.addView(adItemLayout);
            }

        } else {
            vpAds.setVisibility(View.GONE);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (newbieIndexHandler != null && newbieIndexHandler.needCap()) {
            tryCaptureNewbie();
        }

        AmapWeatherManager.INSTANCE.getWeatherLiveData().observe(this, new Observer<WeatherData>() {
            @Override
            public void onChanged(@Nullable WeatherData weatherData) {
                if (weatherData != null && weatherData.completed()) {

                    WeatherDO weatherDO = new WeatherDO();
                    weatherDO.city = weatherData.getLiveWeather().getCity();
                    weatherDO.weather = weatherData.getLiveWeather().getWeather();
                    weatherDO.temp = weatherData.getLiveWeather().getTemperature() + getString(R.string.temperature_symbol);

                    weatherDO.washCar = weatherData.getWashCarDesc();
                    weatherDO.weatherIcon = WeatherUtils.INSTANCE.getWeatherIconUri(weatherDO.weather, false);

                    showWeather(weatherDO);

                } else {
                    showWeather(null);
                }

            }
        });


//    handler.postDelayed(new Runnable() {
//      @Override
//      public void run() {
//        //Tips.show(requireContext());
//        Tips.show2(((FrameLayout) getView()),requireContext());
//      }
//    },1500);

    }

    private void tryCaptureNewbie() {

        imgAvatar.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                final View view = imgAvatar;

                if (imgAvatar.getLeft() > 0) {
                    imgAvatar.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                    int[] point = new int[2];
                    view.getLocationOnScreen(point);

                    RectF rect = new RectF();

                    rect.right = point[0] + view.getWidth() + SizeUtils.dp2px(5);
                    rect.bottom = point[1] + view.getHeight();

                    rect.top = point[1];
                    rect.left = point[0] - SizeUtils.dp2px(90);


                    rect.top -= SizeUtils.dp2px(5);
                    rect.bottom += SizeUtils.dp2px(5);

                    if (newbieIndexHandler != null) {
                        newbieIndexHandler.capScreen(rect);
                    }

                }


            }
        });


    }

    @Override
    public void onStart() {
        super.onStart();
        if (!isShowTop() && homeAdController != null) {
            homeAdController.changeShowAutoScroll(true);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (homeAdController != null) {
            homeAdController.changeShowAutoScroll(false);
        }

    }

    /**
     * 选择城市
     */
    private void onClickCity() {
        startActivityForResult(ChooseCityActivity.Companion.startCityWZ(getContext()), REQ_CHOOSE_CITY);
        StatTools.sendClick(getContext(), StatisticsId.main_city);
    }

    /**
     * 点击天气
     */
    private void onClickWeather() {
        StatTools.sendClick(getContext(), StatisticsId.main_weather);
        WeatherData value = AmapWeatherManager.INSTANCE.getWeatherLiveData().getValue();
        if (value != null && value.completed()) {
            RouterUtils.start(getContext(), RPaths.weather);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == REQ_CHOOSE_CITY) {
                ICity city = data.getParcelableExtra(Constants.EXTRA_DATA_CHOOSE_CITY);
                if (city != null) {
                    mPresenter.changeCity(city);
                }

            }


        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (tvCity != null) {
            tvCity.setText(LocManager.getInstance().getDisplayCityName());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AmapWeatherManager.INSTANCE.getWeatherLiveData().removeObservers(this);
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }

        handler.removeCallbacksAndMessages(null);
    }


    @Override
    public void updateCarInfo(final UserCarInfo userCarInfo) {
        //adapter.update(userCarInfo);
        homeCarController.update(userCarInfo);
        indicatorView.useDefaultColors(homeCarController.getCount());
        indicatorView.setSelectedPosition(mViewPager.getCurrentItem());

        if (userCarInfo.extraError != null) {
            //错误处理
            if (userCarInfo.extraError.exceptionCode == 801) {

                DialogFactory.create(getContext(), "接口暂时维护",
                        "交管局接口暂时维护，暂不支持该地区查询，给您带来的不变，敬请谅解。",
                        "我知道了", null).show();

            } else if (userCarInfo.extraError.exceptionCode == 802) {
                StringBuilder sb = new StringBuilder("交管局查询接口有调整");

                DialogFactory.create(getContext(), "车架号/发动机号规则变化",
                        sb.toString(),
                        "去编辑", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                AddCarInfoActivity.Companion.edit(getContext(), userCarInfo);

                            }
                        }).show();

            }

        }
    }

    @Override
    public void deleteCar(int carId) {
        //adapter.deleteCar(carId);
        homeCarController.deleteCar(carId);
        indicatorView.useDefaultColors(homeCarController.getCount());
        indicatorView.setSelectedPosition(mViewPager.getCurrentItem());
    }

    @Override
    public void showMyCars(List<UserCarInfo> carInfos) {
        setRefreshing(false);
        if (carInfos == null || carInfos.isEmpty()) {
            carInfos = new ArrayList<>();
            carInfos.add(null);
        } else {
            carInfos.add(null);
        }
        int size = carInfos.size();
        //有车，随机取一条
        if (!isShownNotify && size > 1) {
            //通知显示
            UserCarInfo carInfo = carInfos.get(Random.Default.nextInt(0, size - 1));
            if (carInfo != null && !carInfo.isError) {
                Message message = Message.obtain(handler, MSG_SHOW_CAR_TIP, carInfo);
                message.obj = carInfo;
                handler.sendMessageDelayed(message, 5000);

                isShownNotify = true;
            }

        }

        indicatorView.useDefaultColors(size);

        homeCarController.setData(carInfos);

        mViewPager.setCurrentItem(mViewPager.getCurrentItem());

        indicatorView.setSelectedPosition(mViewPager.getCurrentItem());
    }

    @Override
    public void showCity(String city) {
//    if (TextUtils.isEmpty(tvCity.getText())) {
//
//    }
        tvCity.setText(city);
    }

    @Override
    public void showWeather(WeatherDO weatherDO) {
        if (weatherDO == null) {
            imgAvatar.setVisibility(View.GONE);
            tvWeatherTemp.setVisibility(View.GONE);
            tvWeather.setVisibility(View.GONE);
        } else {
            imgAvatar.setVisibility(View.VISIBLE);
            tvWeatherTemp.setVisibility(View.VISIBLE);
            tvWeather.setVisibility(View.VISIBLE);
            tvWeatherTemp.setText(weatherDO.temp + " " + weatherDO.weather);
            tvWeather.setText(weatherDO.washCar);
            imgAvatar.setImageURI(weatherDO.weatherIcon);
        }


    }

    @Override
    public void showCategory(Map<String, List<ExtModule>> map) {
        if (map != null) {
            layoutContent.removeAllViewsInLayout();
            Set<Entry<String, List<ExtModule>>> entries = map.entrySet();
            List<ExtModule> list = new ArrayList<>();
            for (Entry<String, List<ExtModule>> entry : entries) {
                list.addAll(entry.getValue());
            }
            HomeCategoryLayout layout = new HomeCategoryLayout(layoutContent.getContext());
            layout.setLineMaxItem(5);
            //layout.setBackgroundColor(Color.WHITE);
            layout.showCategory(list);
            layout.setOnItemClickListener(new ModuleItemClickListener(StatisticsId.clickHomeModule));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            //lp.topMargin = SizeUtils.dp2px(10);
            layoutContent.addView(layout, lp);
//      layoutContent.addView(new Space(layoutContent.getContext()), LayoutParams.MATCH_PARENT,
//          SizeUtils.dp2px(10));
        }
    }

    @Override
    public void showExtModules(Map<LabelModel, List<ExtModule>> map) {
        final LinearLayout layout = layoutExtModules;
        if (map != null && !map.isEmpty()) {
            layout.setVisibility(View.VISIBLE);
            layout.removeAllViewsInLayout();
            Set<Entry<LabelModel, List<ExtModule>>> entries = map.entrySet();
            for (Entry<LabelModel, List<ExtModule>> entry : entries) {
                HomeExtSModulesLayout modulesLayout = new HomeExtSModulesLayout(layout.getContext());
                modulesLayout.showData(entry.getKey(), entry.getValue());
                modulesLayout.setItemDataOnItemClickListener(new ModuleItemClickListener(StatisticsId.clickHomeModule));
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                        LayoutParams.WRAP_CONTENT);
                //lp.topMargin = SizeUtils.dp2px(10);
                layout.addView(modulesLayout, lp);
            }
        } else {
            layout.setVisibility(View.GONE);
        }
    }

    @Override
    public void setRefreshing(boolean refreshing) {

        if (!refreshing) {
            refreshLayout.finishRefresh(1000);
        }

    }

    @Override
    public void showNewsCategory(final List<NewsCategory> data) {
        if (data == null || data.isEmpty() || !isAdded()) {
            return;
        }

        final List<NewsCategory> list = new ArrayList<>(5);

        if (data.size() < 5) {
            list.addAll(data);
        } else {
            list.addAll(data.subList(0, 5));
        }

        final String[] arrays = new String[list.size()];
        int i = 0;
        for (NewsCategory newsCategory : list) {
            arrays[i++] = newsCategory.name;
        }

        if (tabLayout.getTabCount() > 0) {
            //如果已经添加过，需要先移除，否则下次刷新无法懒加载，不走onCreateView
            tabLayout.removeAllTabs();
            FragUtils.removeAll(getChildFragmentManager());

        }


        for (String array : arrays) {
            tabLayout.addTab(tabLayout.newTab().setText(array));
        }

        tabLayout.setupWithViewPager(vpNews);
        vpNews.setOffscreenPageLimit(5);

        currNewsFragment = null;

        vpNews.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {

            @Override
            public int getCount() {
                return arrays.length;
            }

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
                if (object instanceof HomeNewsFragment) {
                    currNewsFragment = ((HomeNewsFragment) object);

                    currNewsFragment.rvOnScrollListener = HomeFragment.this;
                }
            }

            @Override
            public Fragment getItem(int position) {
                return HomeNewsFragment.newInstance(list.get(position));
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return arrays[position];
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }
        });

        vpNews.clearOnPageChangeListeners();

        vpNews.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                StatTools.sendShow(getContext(), StatisticsId.click_News_Type, list.get(position).type);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        indicator.setTabLayoutAndViewPager(tabLayout, vpNews);
        tabLayout.requestLayout();
    }


    @Override
    public boolean isShowTop() {

        return showScrollTop;
    }

    @Override
    public void scrollTop() {

        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) appBarLayout
                .getLayoutParams();
        if (lp.getBehavior() instanceof HomeBehavior) {

            HomeBehavior behavior = (HomeBehavior) lp.getBehavior();

            int topAndBottomOffset = behavior.getTopAndBottomOffset();
            if (topAndBottomOffset != 0) {
                behavior.scrollTop();
                behavior.setTopAndBottomOffset(0);
            }

        }


    }

    @Override
    public void onScrollStateChanged(int newState) {

        if (adFloat != null) {

            switch (newState) {
                case RecyclerView.SCROLL_STATE_IDLE:
                    //停止
                    //显示广告

                    handler.removeMessages(MSG_SHOW_FLOAT_AD);
                    handler.sendEmptyMessageDelayed(MSG_SHOW_FLOAT_AD, 200);

                    break;
                case RecyclerView.SCROLL_STATE_DRAGGING:
                    //滑动中
                    //隐藏广告
                    handler.removeMessages(MSG_SHOW_FLOAT_AD);
                    if (adFloat.getTranslationX() == 0f) {

                        //SizeUtils.dp2px(70)
                        ObjectAnimator.ofFloat(adFloat, View.TRANSLATION_X, 0f, screenW - adFloat.getLeft()).start();
                    }

                    break;
                case RecyclerView.SCROLL_STATE_SETTLING:
                    break;
            }

        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (homeAdController != null) {
            homeAdController.changeShowAutoScroll(!hidden);
        }

    }

    private Handler handler = new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == MSG_SHOW_FLOAT_AD) {

                if (adFloat != null) {
                    ObjectAnimator.ofFloat(adFloat, View.TRANSLATION_X, adFloat.getTranslationX(), 0).start();
                }

                return true;
            } else if (msg.what == MSG_SHOW_CAR_TIP) {
                if (isVisible() && msg.obj instanceof UserCarInfo) {

                    try {
                        if (MainActUtils.diffTime() > 3000) {
                            Tips.showView(((FrameLayout) getView()), requireContext(), ((UserCarInfo) msg.obj));
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                        BizReport.postCatchedException(e);
                    }
                }

                return true;
            }
            return false;
        }
    });


}
